//
//  CVSampleBasicViewController.m
//  CVSampleBasic
//
//  Created by  Artem on 12.08.11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CVSampleBasicViewController.h"
#import "CVImageConverter.h"

@implementation CVSampleBasicViewController
@synthesize scrollView;
@synthesize imageView;
@synthesize pickerView;
@synthesize textField;
@synthesize slider;
@synthesize blurSegmentedControl;
@synthesize loadSegmentedControl;
@synthesize activityIndicator;
@synthesize loadImageButton;
@synthesize blurImageButton;
@synthesize saveImageButton;
@synthesize cancelButton;

@synthesize pickerViewArraySample;
@synthesize pickerViewArraySaved;
@synthesize fileName;

-(void)loadCVImageFromFile:(NSString *)theFileName {
    cv_image.release();
    cv_image = cv::imread([theFileName fileSystemRepresentation]);
}

-(void)saveCVImageToFile:(NSString *)theFileName {
    try {
        cv::imwrite([theFileName fileSystemRepresentation], cv_image);
    } catch (cv::Exception exeption) {
       
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                        message:[NSString stringWithCString:exeption.err.c_str() 
                                                                                   encoding:[NSString defaultCStringEncoding]]
                                                       delegate:self 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles: nil];
        [alert show];	
        [alert release];
    }
    
}

-(int)FilterSizeFromFloatValue:(float)theValue {
    
    int filterSize = (int) (theValue * 30) + 1; 
    filterSize += (filterSize+1)%2;
    return filterSize;
}

// ToDo: run this in a different thread

-(cv::Mat)blurImageWithFilterSized:(int)theFilterSize {
   
    cv::Mat dst = cv_image.clone();
    switch (self.blurSegmentedControl.selectedSegmentIndex)
	{
		case 0:	// Homogeneous
		{
            cv::blur( cv_image, dst, cv::Size( theFilterSize, theFilterSize), cv::Point(-1,-1)); 
			break;
		}
		case 1: // Gaussian
		{	
            cv::GaussianBlur(cv_image, dst, cv::Size( theFilterSize, theFilterSize), 0);			
			break;
		}
        case 2:	// Median
		{
            cv::medianBlur( cv_image, dst, theFilterSize); 
			break;
		}
		case 3: // Bilateral
		{	
            cv::bilateralFilter(cv_image, dst, theFilterSize, theFilterSize*2, theFilterSize/2);			
			break;
		}
    }

    //[self.activityIndicator stopAnimating];
    //self.activityIndicator.hidden = YES;
    return dst;
}

- (void)dealloc
{
    [scrollView release];
    [imageView release];
    [pickerView release];
    [textField release];

    [pickerViewArraySaved release];
    [pickerViewArraySample release];
    [fileName release];
    
    [loadImageButton release];
    [blurImageButton release];
    [saveImageButton release];
    [cancelButton release];
    [slider release];
    [blurSegmentedControl release];
    [loadSegmentedControl release];
    [activityIndicator release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    scrollView.delegate = self;
    pickerView.delegate = self;
    pickerView.dataSource = self;
    textField.delegate = self;
    
    self.loadImageButton.possibleTitles = [NSSet setWithObjects:@"Load", @"Done", nil];
    self.blurImageButton.possibleTitles = [NSSet setWithObjects:@"Blur", @"Done", nil];
    self.saveImageButton.possibleTitles = [NSSet setWithObjects:@"Save", @"Done", nil];

  
    // To set buttons into default view
    [self cancelAction:cancelButton];
    
    
    self.fileName = [[NSBundle mainBundle] pathForResource:@"lena" ofType:@"png"];
    [self loadCVImageFromFile:fileName];
   
    
        
    self.pickerViewArraySample = [NSArray arrayWithObjects:@"cat.jpg", @"fruits.jpg", @"lena.png", nil];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    self.pickerViewArraySaved = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL];
    
    scrollView.contentSize = imageView.bounds.size;
    scrollView.minimumZoomScale = 1.0;
    scrollView.maximumZoomScale = 2.0;

}


- (void)viewDidUnload
{
    [self setScrollView:nil];
    [self setImageView:nil];
    [self setPickerView:nil];
    [self setTextField:nil];
    
    [self setPickerViewArraySaved:nil];
    [self setPickerViewArraySample:nil];
    [self setFileName:nil];
    
    [self setLoadImageButton:nil];
    [self setBlurImageButton:nil];
    [self setSaveImageButton:nil];
    [self setCancelButton:nil];
    [self setSlider:nil];
    [self setBlurSegmentedControl:nil];
    [self setLoadSegmentedControl:nil];
    [self setActivityIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
{
    return imageView;
}


#pragma mark - UIPickerViewDelegate


-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (self.loadSegmentedControl.selectedSegmentIndex) {
        case 1: {
            return [pickerViewArraySaved objectAtIndex:row];
            break;
        }
        default: {
            return [pickerViewArraySample objectAtIndex:row];
            break;
        }
    }
}

#pragma mark - UIPickerViewDataSource

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 
{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (self.loadSegmentedControl.selectedSegmentIndex) {
        case 1: {
            return [pickerViewArraySaved count];
            break;
        }
        default: {
            return [pickerViewArraySample count];
            break;
        }
    }
}

#pragma mark - UITextFieldDelegate

-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        if (theTextField == textField) {
        [textField resignFirstResponder]; 
    }
    return YES;
}



- (IBAction)loadImageSelected:(id)sender {
    self.pickerView.hidden = NO;
    self.loadSegmentedControl.hidden = NO;
    self.blurImageButton.enabled = NO;
    self.saveImageButton.enabled = NO;
    self.cancelButton.enabled = YES;
    
    self.loadImageButton.style = UIBarButtonItemStyleDone;
    self.loadImageButton.title = @"Done";
    self.loadImageButton.action = @selector(loadImageDone:);
    
    [self loadSourceChanged:loadSegmentedControl];
    
}

- (IBAction)loadImageDone:(id)sender {
    switch (self.loadSegmentedControl.selectedSegmentIndex) {
        case 0: {
            NSString *selectedFileName = [pickerViewArraySample objectAtIndex:[pickerView selectedRowInComponent:0]]; 
            
            self.fileName = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:selectedFileName];
            break;
        }
        case 1: {
            NSString *selectedFileName = [pickerViewArraySaved objectAtIndex:[pickerView selectedRowInComponent:0]]; 
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            self.fileName = [documentsDirectory stringByAppendingPathComponent:selectedFileName];
            break;
        }
    }

    [self loadCVImageFromFile:fileName];
    
    UIImage *image = [CVImageConverter UIImageFromCVMat:cv_image withError:NULL];
    
    if (image != nil) {
       imageView.image = image;
    }
    
    [self cancelAction:cancelButton];
    
}

- (IBAction)loadSourceChanged:(id)sender {
    if (self.loadSegmentedControl.selectedSegmentIndex == 1) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        self.pickerViewArraySaved = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL];

    }
    [self.pickerView reloadAllComponents];
}

- (IBAction)blurImageSelected:(id)sender {
    self.slider.hidden = NO;
    self.blurSegmentedControl.hidden = NO;
    self.loadImageButton.enabled = NO;
    self.saveImageButton.enabled = NO;
    self.cancelButton.enabled = YES;
    
    self.blurImageButton.style = UIBarButtonItemStyleDone;
    self.blurImageButton.title = @"Done";
    self.blurImageButton.action = @selector(blurImageDone:);
}

- (IBAction)blurImageDone:(id)sender {
    
    int filterSize = [self FilterSizeFromFloatValue:slider.value];
    
    cv::Mat dst = [self blurImageWithFilterSized:filterSize];

    cv_image = dst;
    
    [self cancelAction:cancelButton];
}

- (IBAction)saveImageSelected:(id)sender {
    self.textField.hidden = NO;
    self.loadImageButton.enabled = NO;
    self.blurImageButton.enabled = NO;
    self.cancelButton.enabled = YES;
    
    self.saveImageButton.style = UIBarButtonItemStyleDone;
    self.saveImageButton.title = @"Done";
    self.saveImageButton.action = @selector(saveImageDone:);
}

- (IBAction)saveImageDone:(id)sender {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString* documentsDir = [paths objectAtIndex:0];
    
    NSString *typedName = textField.text;
    
    self.fileName = [documentsDir stringByAppendingPathComponent:typedName];
    textField.text = [NSString string];
    
    [self saveCVImageToFile:fileName];
    
    [self cancelAction:cancelButton];
}

- (IBAction)cancelAction:(id)sender {
    self.pickerView.hidden = YES;
    self.textField.hidden = YES;
    self.slider.hidden = YES;
    self.loadSegmentedControl.hidden = YES;
    self.blurSegmentedControl.hidden = YES;
    
    self.loadImageButton.style = UIBarButtonItemStyleBordered;
    self.loadImageButton.title = @"Load";
    self.loadImageButton.action = @selector(loadImageSelected:);
    self.loadImageButton.enabled = YES;
    
    self.blurImageButton.style = UIBarButtonItemStyleBordered;
    self.blurImageButton.title = @"Blur";
    self.blurImageButton.action = @selector(blurImageSelected:);
    self.blurImageButton.enabled = YES;
    
    self.saveImageButton.style = UIBarButtonItemStyleBordered;
    self.saveImageButton.title = @"Save";
    self.saveImageButton.action = @selector(saveImageSelected:);
    self.saveImageButton.enabled = YES;
    self.cancelButton.enabled = NO;
}

- (IBAction)ApplyBlurAction:(id)sender {
    
    //self.activityIndicator.hidden = NO;
    //[self.activityIndicator startAnimating];
    
    int filterSize = [self FilterSizeFromFloatValue:slider.value];
    
   
    
    cv::Mat dst = [self blurImageWithFilterSized:filterSize];
    
    UIImage *image = [CVImageConverter UIImageFromCVMat:dst withError:NULL];
    
    if (image != nil) {
        imageView.image = image;
    }    
    
    
    
}
@end
